#!/bin/bash

# 设置默认参数
ARCH=${1:-"amd64"}
IMAGE_NAME="xinfang:latest"
PLATFORM="linux/${ARCH}"

# 切换到项目根目录
cd "$(dirname "$0")"
PROJECT_ROOT=$(pwd)

echo "===== 开始构建 XINFANG API 镜像 (${ARCH}) ====="

# 检查项目必要文件是否存在
if [ ! -f "${PROJECT_ROOT}/requirements.txt" ]; then
    echo "错误: 未找到 requirements.txt 文件"
    exit 1
fi

# 确保目录存在
OUTPUT_DIR=${PROJECT_ROOT}/docker/output/xinfang-${ARCH}
mkdir -p ${OUTPUT_DIR}/images

# 检查docker buildx是否可用
if docker buildx version >/dev/null 2>&1; then
    USE_BUILDX=true
    echo "使用 docker buildx 构建多架构镜像..."
else
    USE_BUILDX=false
    echo "docker buildx 不可用，使用标准 docker build 命令..."
    # 如果当前平台和目标架构不匹配，给出警告
    if [[ "${ARCH}" != "$(uname -m)" && "${ARCH}" != "amd64" && "$(uname -m)" != "x86_64" ]]; then
        echo "警告: 当前系统架构 ($(uname -m)) 与目标构建架构 (${ARCH}) 不匹配"
        echo "使用标准 docker build 可能无法正确构建跨架构镜像"
        echo "建议安装 docker buildx 以支持跨平台构建"
        
        read -p "是否继续构建? (y/n) " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            echo "已取消构建"
            exit 1
        fi
    fi
fi

# 构建镜像
echo "构建 XINFANG API 镜像 (${ARCH})..."
for attempt in {1..3}; do
    echo "尝试构建 XINFANG API 镜像 (第${attempt}次)..."
    
    if [ "$USE_BUILDX" = true ]; then
        docker buildx build \
            --platform ${PLATFORM} \
            --build-arg TARGETPLATFORM=${PLATFORM} \
            --build-arg TARGETARCH=${ARCH} \
            -t ${IMAGE_NAME} \
            -f Dockerfile \
            --load . && break
    else
        docker build \
            --build-arg TARGETPLATFORM=${PLATFORM} \
            --build-arg TARGETARCH=${ARCH} \
            -t ${IMAGE_NAME} \
            -f Dockerfile \
            . && break
    fi
    
    if [ $attempt -lt 3 ]; then
        echo "构建失败，2秒后重试..."
        sleep 2
    fi
done

# 检查构建结果
if [ $? -ne 0 ]; then
    echo "XINFANG API 镜像构建失败!"
    exit 1
fi

# 保存镜像
echo "保存 XINFANG API ${ARCH} 版本镜像..."
docker save ${IMAGE_NAME} > ${OUTPUT_DIR}/images/xinfang-api-linux_${ARCH}.tar.gz

echo "===== XINFANG API 镜像构建完成 ====="
echo "镜像已保存至: ${OUTPUT_DIR}/images/xinfang-api-linux_${ARCH}.tar.gz" 